package com.sctvcloud.dongqu.ui.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.beans.NewsDate;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.beans.Titles;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.adapter.NewsListAdapter;
import com.sctvcloud.dongqu.ui.util.IListShowData;
import com.sctvcloud.dongqu.ui.utils.MutilDateNewsGetHelper;
import com.sctvcloud.dongqu.utils.ListTypeUtils;
import com.sctvcloud.dongqu.utils.ResultAsyncTask;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 时讯的
 * A simple {@link Fragment} subclass.
 */
public class NewsListFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {
    @BindView(R.id.news_list_refresh)
    protected CanRefreshLayout refreshLayout;

    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;

    private MutilDateNewsGetHelper hour24GetHelper;
    private NewsListAdapter adapter;


    public NewsListFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        refreshLayout.setLoadMoreEnabled(false);

    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        if (isFirst) {
            refreshLayout.autoRefresh();
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onRefresh() {
//        doTestDataGet();
        getNews24Date();
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            getNews24Page(false);
        }
    }


    /**
     * 首次请求、下拉刷新加载数据
     * @return
     */
    private boolean getNews24Date() {
        if (TextUtils.isEmpty(channelUrl)) {
            JLog.e("int " + this.getClass().getSimpleName() + " 24h url wrong ::" + channelUrl);
            return false;
        }
        NetUtils.getNetAdapter().getNewsDateArray(getOwnerName(), channelUrl, new AbsListNetCallback<NewsDate>(ListTypeUtils.NewsItem()) {
            boolean b = true;

            @Override
            public void onSuc(List<NewsDate> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    if (DateUtils.getCurrentOnlyDateMil() == -1 ||
                            !android.text.format.DateUtils.isToday(DateUtils.getCurrentOnlyDateMil())) {
                        DateUtils.initOnlyDate();
                    }
                    init24Helper().setDates(newsItems);

                    b = !getNews24Page(true);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (b) {
                    refreshLayout.refreshComplete();
                }
            }
        });
        return true;
    }

    /**
     * 加载更多数据
     * @param reset
     * @return
     */
    private boolean getNews24Page(final boolean reset) {
        if (!init24Helper().hasValuedDate()) {
            if (reset) {
                if (adapter != null) {
                    adapter.clean();
                }
            }
            return false;
        }
        hour24GetHelper.getNewsList(20, reset
                , new AbsListNetCallback<IListShowData>(IListShowData.class) {

                    @Override
                    public void onSuc(List<IListShowData> newsItems) {
                        setData(newsItems, reset);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        if (reset) {
                            refreshLayout.refreshComplete();
                        } else {
                            refreshLayout.loadMoreComplete();
                        }
                        boolean b = !hour24GetHelper.hasGetAll();
                        refreshLayout.setLoadMoreEnabled(b);
                    }
                });
        return true;
    }

    private void setData(List<IListShowData> list, boolean reset) {
        if (ListUtils.isListValued(list)) {
            if (adapter == null) {
                adapter = new NewsListAdapter(getContext(), list);
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("页面", "首页"));
                pairs.add(new Pair<>("栏目", "时讯"));
                adapter.setFragment(this);
                adapter.setPairs(pairs);
                recyclerView.setAdapter(adapter);
            } else {
                if (reset) {
                    adapter.setData(list);
                } else {
                    int pos = adapter.getItemCount();
                    adapter.addDatas(list);
                    if (pos > 0) {
                        adapter.notifyItemChanged(pos - 1);
                    }
                }
            }
        } else {
            if (reset) {
                if (adapter != null) {
                    adapter.clean();
                }
            }
        }
    }
    @Override
    public void onDestroyView() {
        if (refreshLayout != null) {
            refreshLayout.setOnRefreshListener(null);
            refreshLayout.setOnLoadMoreListener(null);
        }
        super.onDestroyView();
    }


    private MutilDateNewsGetHelper init24Helper() {
        if (hour24GetHelper == null) {
            hour24GetHelper = new MutilDateNewsGetHelper(this);
            hour24GetHelper.setShouldSetTitleAfter(true);
        }
        return hour24GetHelper;
    }


    private List<IListShowData> getTestData() {
        ArrayList<IListShowData> list = new ArrayList<>();
        Titles t = new Titles();
        t.setTitle("06月12日");
        t.setDateString("06月12日");
        t.setViewType(NewsListAdapter.VIEWTYPE_TITLE_24);
        list.add(t);
        NewsItem ni = null;
        for (int i = 0; i < 6; i++) {
            ni = NewsItem.createTestInstance(i, NewsListAdapter.VIEWTYPE_NEWS_24);
            list.add(ni);
        }
        t = new Titles();
        t.setTitle("06月11日");
        t.setDateString("06月11日");
        t.setViewType(NewsListAdapter.VIEWTYPE_TITLE_24_CONTINUE);
        list.add(t);
        for (int i = 0; i < 6; i++) {
            ni = NewsItem.createTestInstance(i == 0 ? -2 : i, NewsListAdapter.VIEWTYPE_NEWS_24);
            list.add(ni);
        }
        return list;
    }

    private void doTestDataGet() {
        new ResultAsyncTask<List<IListShowData>>() {

            @Override
            protected List<IListShowData> doInBackground(Void... params) {

                try {
                    Thread.sleep((long) (100 + Math.random() * 8000));//模拟网络延时
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getTestData();
            }

            @Override
            protected void onPostExecute(List<IListShowData> iListShowDatas) {
                if (adapter == null) {
                    adapter = new NewsListAdapter(getContext(), iListShowDatas);
                    recyclerView.setAdapter(adapter);
                } else {
                    adapter.setData(iListShowDatas);
                }
                refreshLayout.refreshComplete();
            }
        }.ex();
    }

}
